﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PraiseSystem.Domain.Entities;
using System.Reflection;
using System.Data.Entity.ModelConfiguration;

namespace PraiseSystem.Domain.Concrete
{
    public class EFDbContext:DbContext
    {
        public virtual DbSet<Praise> Praises { get; set; }
        public virtual DbSet<User> Users { get; set; }
        public virtual DbSet<Receiver> Receivers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Get mapping types derived from EntityTypeConfiguration
            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(type => !string.IsNullOrEmpty(type.Namespace))
                .Where(type => type.BaseType != null
                && type.BaseType.IsGenericType
                && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

            //Register types.
            foreach (var type in typesToRegister)
            {
                dynamic configInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configInstance);
            }

            base.OnModelCreating(modelBuilder);
        }
    }
}
